package cn.zjjd.homeworkserver.util;

import cn.zjjd.homeworkserver.pojo.DeviceInfluxDB;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: 小胡
 * @create: 2022/12/21
 * @Description:
 * @FileName: WebSocket
 * @Version: 1.0
 */
@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocketServer {
    private static InfluxDB influxDB;
    @Autowired
    public void setInfluxDB(InfluxDB influxDB){
        WebSocketServer.influxDB = influxDB;
    }
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 当前在线连接数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 用来存放每个客户端对应的 WebSocketServer 对象
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收 userId
     */
    private String userId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
            addOnlineCount();
        }
        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    QueryResult rs = influxDB.query(new Query("select * from devices", "position"));
                    HashMap<String,Object> sendmsg = new HashMap<>();
                    if (!rs.hasError() && !rs.getResults().isEmpty()) {
                        for (List<Object> objs:rs.getResults().get(0).getSeries().get(0).getValues()) {
                            DeviceInfluxDB dev = new DeviceInfluxDB();
                            dev.setDeviceName(String.valueOf(objs.get(1)));
                            dev.setLng(String.valueOf(objs.get(4)));
                            dev.setLat(String.valueOf(objs.get(3)));
                            HashMap<String,String> pro = new HashMap<>();
                            pro.put("temp",String.valueOf(objs.get(5)));
                            pro.put("humi",String.valueOf(objs.get(2)));
                            dev.setProperty(pro);
                            sendmsg.put(String.valueOf(objs.get(1)),dev);
                        }
                    }
                    JSONObject jsonObj = new JSONObject(sendmsg);
                    sendMessage(jsonObj.toJSONString());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("用户:" + userId + ",网络异常!!!!!!");
                }
            }
        }, 5000, 20000);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:" + userId + ",报文:" + message);
        if (!StringUtils.isEmpty(message)) {
            try {
                JSONObject jsonObject = JSON.parseObject(message);
                jsonObject.put("fromUserId", this.userId);
                String toUserId = jsonObject.getString("toUserId");
                if (!StringUtils.isEmpty(toUserId) && webSocketMap.containsKey(toUserId)) {
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                } else {
                    log.error("请求的 userId:" + toUserId + "不在该服务器上");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static synchronized AtomicInteger getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount.getAndIncrement();
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount.getAndDecrement();
    }
}
